package com.general.common.action;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FilenameUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.StrutsStatics;
import org.springframework.cglib.core.EmitUtils;

import com.general.utils.base.Constant;
import com.opensymphony.xwork2.ActionContext;

/**
 * 导出EXCEL
 * @author qilm
 *
 */
public class DownloadExcelAction extends BaseAction {
	private static final long serialVersionUID = 1L;
	private String fileName; // 文件名
	private String tempPath; // 临时文件目录
	InputStream excelStream;
	public String execute() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(StrutsStatics.HTTP_REQUEST); 
		String ids = request.getParameter("ids");
		initExcel(ids);
		return "success";
	}
	
	/**
	 * 将最新的数据插入excel
	 */
	public void initExcel(String ids) {
		List list = new ArrayList();
		// 这里是获取需要填充的数
		// list = XXXService().getXXX();
		// excel模板绝对路径
		String path = "/excel/templet/";
		try {
			String filepath = ServletActionContext.getServletContext()
					.getRealPath(path + fileName + ".xls");
			//FileInputStream fis = new FileInputStream(filepath);
			
			//this.fileName = createFileName();		

			HSSFWorkbook wb = new HSSFWorkbook();
			
			// ==============开始生成excel=======================
			HSSFSheet sheet = wb.createSheet();

			//设置为水平居中  
			HSSFCellStyle centerStyle = wb.createCellStyle();
	        centerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
	        centerStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); 

	        HSSFRow row1 = sheet.createRow((short) 0);
	        createCell(row1, 0, "360问卷调查", centerStyle);
	        
	        workbook2InputStream(wb,createFileName());
			//初始化
			//this.initSheet(sheet);
//			ExcelUtils eu = new EmitUtils();
//			tempPath = eu.exportExcel(fis, "temp/" + createFileName(),
//					fileName, list);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**  
	    * 创建单元格  
	    * @param row 行  
	    * @param column 列位置  
	    * @param value 值  
	    * @param style 样式  
	    */  
	   private void createCell(HSSFRow row,int column,Object value,HSSFCellStyle style){  
	       HSSFCell cell = row.createCell((short)column);  
	       //((Object) cell).setEncoding((short) 1);  
	       cell.setCellValue(String.valueOf(value));  
	       cell.setCellStyle(style);  
	   }
	   
	/**
	 * 将Workbook写入到InputStream
	 * @param workbook
	 * @param fileName
	 * @throws Exception
	 */
	private void workbook2InputStream(HSSFWorkbook workbook,String fileName) throws Exception{
		this.fileName = fileName; //设置fileName          
		ByteArrayOutputStream baos = new ByteArrayOutputStream();         
		workbook.write(baos);          
		baos.flush();           
		byte[] aa = baos.toByteArray();          
		excelStream = new ByteArrayInputStream(aa, 0, aa.length);         
		baos.close();
	}
	/**
	 * 以年月日时分秒毫秒+4位随机数的格式来创建一个文件名，不带扩展名
	 * 
	 * @return 文件名
	 */
	public static String createFileName() {
		StringBuffer sb = new StringBuffer();
		Date date = new Date();
		// 获取年月日时分秒
		sb.append(new SimpleDateFormat("yyyyMMddHHmmss").format(date));
		// 毫秒
		String milli = String.valueOf(date.getTime() % 1000);
		while (milli.length() < 3) {
			milli = "0" + milli;
		}
		sb.append(milli);
		// 四位随机数
		String rondom = String.valueOf(new Random().nextInt(10000));
		while (rondom.length() < 4) {
			rondom = "0" + rondom;
		}
		sb.append(rondom);
		return sb.toString();
	}
	
	public String getTempPath() {
		return tempPath;
	}

	public void setTempPath(String tempPath) {
		this.tempPath = tempPath;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public InputStream getExcelStream() {
		return excelStream;
	}

	public void setExcelStream(InputStream excelStream) {
		this.excelStream = excelStream;
	}
}

